/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = 'penging';
const FULFILLED = ' fulfilled';
const REJECTED = 'rejected';

class LXLPromise {
  // 1.传递执行器，执行器立即执行。
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (error) {
      this.reject(error);
    }
  }
  // 初始化状态
  status = PENDING;
  // 成功的值
  value = undefined;
  // 失败的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];
  // 更改为成功状态
  resolve = (value) => {
    if (this.status !== PENDING) return;
    // 设置成功状态
    this.status = FULFILLED;

    // 保存成功后的值
    this.value = value;
    // 判断成功回调是否存在，存在就调用
    while (this.successCallback.length) this.successCallback.shift()();
  }

  // 更改为失败状态
  reject = (reason) => {
    if (this.status !== PENDING) return;
    // 设置失败状态
    this.status = REJECTED;

    // 保存失败的原因
    this.reason = reason;
    // 失败回调是否存在，存在就调用
    while (this.failCallback.length) this.failCallback.shift()();
  }

  then(successCallback, failCallback) {
    // 传递successCallback
    successCallback = successCallback ? successCallback : value => value;
    // 传递failCallback
    failCallback = failCallback ? failCallback : reason => { throw reason };

    let promise2 = new LXLPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            //判断 x 是否是LXLPromise对象
            // 是普通值直接调 resolve
            // 是LXLPromise对象， 根据返回结果决定调resolve 或 reject
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error);
          }

        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            //判断 x 是否是LXLPromise对象
            // 是普通值直接调 resolve
            // 是LXLPromise对象， 根据返回结果决定调resolve 或 reject
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error);
          }

        }, 0);
      } else {
        // 等待状态
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              //判断 x 是否是LXLPromise对象
              // 是普通值直接调 resolve
              // 是LXLPromise对象， 根据返回结果决定调resolve 或 reject
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error);
            }

          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              //判断 x 是否是LXLPromise对象
              // 是普通值直接调 resolve
              // 是LXLPromise对象， 根据返回结果决定调resolve 或 reject
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error);
            }

          }, 0);
        });
      }
    });

    return promise2;
  }
  // 不管状态是成功失败都执行一次
  finally(callback) {
    return this.then((value) => {
      return LXLPromise.resolve(callback()).then(() => value);
    }, (reason) => {
      return LXLPromise.resolve(callback()).then(() => { throw reason });
    })
  }
  catch(failCallback) {
    return this.then(undefined, failCallback);
  }

  static all(array) {
    let result = [];
    let index = 0;

    return new LXLPromise((resolve, reject) => {
      // 统一添加返回结果
      function addData(key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          // 返回全部结果
          resolve(result);
        }
      }
      // 循环所有LXLPromise或其他数据
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof LXLPromise) {
          // 执行then addData数据
          current.then(value => addData(i, value), reason => reject(reason));
        } else {
          // 执行 addData数据
          addData(i, array[i])
        }
      }
    })
  }

  static resolve(value) {
    if (value instanceof LXLPromise) return value;
    return new LXLPromise((resolve) => resolve(value));
  }


}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('不能循环调用自己'));
  }
  if (x instanceof LXLPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}

// const promise = new LXLPromise((resolve, reject) => {
  // setTimeout(() => {
  //   resolve('成功');
  // }, 2000);
  // throw Error('executor error')
  // resolve('成功');
  // reject('失败');
// });

// LXLPromise.resolve(100).then(console.log)
// LXLPromise.resolve(p1()).then(console.log)

// function p1() {
//   return new LXLPromise((reslove, reject) => {
//     setTimeout(() => {
//       // reslove('p1111');
//       reject('p1111失败');

//     }, 2000)
//   })
// }

// function p2() {
//   return new LXLPromise((reslove, reject) => {
//     reslove('p22222');
//     // reject('失败');

//   })
// }

// p2().finally(() => {
//   console.log('finally');
//   return p1()
// }).then(console.log).catch(console.log);

// LXLPromise.all(['a', 'b', p1(), p2(), 'c']).then((value) => {
//   console.log(value)
// });

// promise.then(value => {
//   console.log(value)
// }, function (reason) {
//   console.log(reason);
// })
// function other() {
//   return new LXLPromise((resolve, reject) => {
//     resolve('other')
//   });
// }
// promise.then(value => {
//   console.log(value);
// throw Error('then error')
//   return 'aaaa';
// }, function (reason) {
// console.log(reason)
//   return 1000;
// }).then(console.log)

// pr.then((value) => {
//   console.log(value)
// }, function (reason) {
//   console.log(reason.message)
// });

// promise.then().then().then(console.log,
//   console.log
// );